<!DOCTYPE html>
<html>
    <?php
    require_once "../DB/db.php";

    /* --------------- Form values and validation checks ------------- */
    $givenname = '';
    $surename = '';
    $address = '';
    $country = '';
    $zip = '';
    $state = '';
    $error = '';
    $email = '';
    $errorcheck = false;
    $statecheck = false;
    $emailcheck = false;
    $passwordcheck = false;
    $whitespaceerror = false;
    $zipcheck = false;

    /* ------- Validation prosess for the registrer form ------------- */
    if (isset($_POST['givenname'])) {

        foreach ($_POST as $name => $value) { // checks for fields that only contains whitespaces
            if (strlen($value) > 0 && strlen(trim($value)) == 0){
                $error .= "Your " . $name . " field contains only whitespaces!<br >";
                $whitespaceerror = true;
            }
        }
        
        if( strlen($_POST['password']) < 6) { // checks if password is to short
            $error .= "Your password is too short!<br >";
            $passwordcheck = true;
        }    
        
        $res1 = $db->query('SELECT email FROM users');
        while ($row1 = $res1->fetch()) {
            if ($_POST['email'] == $row1['email']) { // checks if email already exists
                $emailcheck = true;
                $error .= "Email is already in use!<br >";
            }
        }
        
        if (!ctype_digit($_POST['zip'])) { // checks if the zip-code is only digits
            $zipcheck = true;
            $error .= "Your zip-code contains illegal characters, legal characters are 0-9!<br >";
        }
        
        if ($_POST['country'] != 'Norway' && $_POST['state'] == '') { // checks if state is filled in
            $statecheck = true;
            $error .= "You forgot to fill in what state you live in!<br >";
        }
        
        if ($emailcheck == true || $statecheck == true || $zipcheck == true || $whitespaceerror == true || $passwordcheck == true) {
            $givenname = $_POST['givenname'];
            $surename = $_POST['surename']; // returns the values to the form
            $address = $_POST['address1'];
            $country = $_POST['country'];
            $zip = $_POST['zip'];
            $state = $_POST['state'];
            $email = $_POST['email'];
            $errorcheck = true;
        }


        /* ------------------- Insert user to database ------------------ */
        if ($errorcheck == false) {
            $sql = 'INSERT INTO users (givenname, surename, address, country, postnr, poststed, email, password, type) values (?, ?, ?, ?, ?, ?, ?, ?, ?)';
            $sth = $db->prepare($sql);
            $res = $db->query('SELECT * from countries ORDER BY cid');
            while ($row = $res->fetch()) {
                if ($row['country'] == $_POST['country']) {
                    $country = $row['cid'];
                    break;
                }
            }
            $pwd = md5($_POST['password']);
            $result = $sth->execute(array($_POST['givenname'], $_POST['surename'], $_POST['address1'], $country, $_POST['zip'], $_POST['state'], $_POST['email'], $pwd, 'user'));
            $userID = $db->lastInsertId();
            if (!$result) {
                $error = 1;
            } else {
                header("Location: ../Functions/authFunctions.php?userID=". $userID); 
            }
        }
    }
    ?>
    <head>
        <title>Nettbutikk</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">   
        <link rel="stylesheet" type="text/css" href="CSS/mainFrame.css" />
        <link rel="stylesheet" type="text/css" href="../CSS/content.css" />
    </head>
    <body>
        <div class="wrapper">
            <?php
            include_once "../MainFrame/header.php";
            include_once "../MainFrame/menuBar.php";
            include_once "../MainFrame/sideBar.php";
            ?>
            <div class="content">
                <h1>Ny kunde? Registrer deg her!</h1>
                <form id="registrer" name="registrer" method="post" action="registrer.php" > 
                    <?php
                    /* --------- display error messages --------------- */
                    if ($error == 1) {
                        echo '<div class="error">Unable to connect to database, please try again later</div>';
                    } else if ($errorcheck == true) {
                        echo '<div class="validation">' . $error . '</div>';
                    }

                    /* ----------- Display registrer form --------------- */
                    echo '<label for="givenname">Fornavn:</label><input name="givenname" type="text" value="' . $givenname . '" required="required" ><br />';
                    echo '<label for="surename">Etternavn:</label><input name="surename" type="text" value="' . $surename . '" required="required"><br />';
                    echo '<label for="address1">Adresse:</label><input name="address1" type="text" value="' . $address . '" required="required"><br />';
                    echo '<label for="country">Land:</label><select name="country"  value="options">';
                    $res = $db->query('SELECT * from countries ORDER BY cid');
                    while ($row = $res->fetch()) {
                        if ($row['country'] == $country) {
                            echo "<option value='{$row['country']}' selected='selected'>{$row['country']}</option>\n";
                        } else {
                            echo "<option value='{$row['country']}'>{$row['country']}</option>\n";
                        }
                    }
                    echo '</select><br />';
                    echo '<label for = "zip">Postnummer:</label><input name = "zip" type = "text" value="' . $zip . '" required = "required"><br />';
                    echo '<label for = "state">Poststed:</label><input name = "state" id="state" type = "text"  value="' . $state . '" placeholder="Not for Norwegian users"><br />';
                    echo '<label for = "email">E-Post:</label><input name = "email" type = "email" value="' . $email . '" required = "required"><br />';
                    echo '<label for = "password">Passord:</label><input name = "password" type = "password" required = "required" placeholder="Between 6-15 characters" maxlength = "15"><br />';
                    echo '<label for = "check">Bekreft:</label><input type = "password" name = "check" data-equals = "password" required = "required" /><br />';
                    echo '<input name = "submit" type = "submit" value = "Opprett" ><input name = "reset" type = "reset" value = "Reset">';
                    ?>
                </form>
            </div>
            <?php
            include_once "../MainFrame/footer.php";
            ?>
        </div>
    </body>
</html>
